<template>
  <div class="container-fluid">
    <el-row :gutter="20">
      <el-button size="default">
        <a
          href="https://docs.qq.com/sheet/DVHFRb0p1QURWQUhC"
          type="primary"
          target="_bank"
          >账号开通模板</a
        >
      </el-button>
      <el-upload
        class="upload-demo"
        action="https://jsonplaceholder.typicode.com/posts/"
        :auto-upload="true"
        :accept="Sheetjsftstring"
        :http-request="request"
        :show-file-list="false"
      >
        <el-button type="primary" size="default">上传文件</el-button>
      </el-upload>
    </el-row>
    <el-row class="margin-top20">
      <el-col>
        <el-table :data="tabledata" border style="width: 100%" max-height="300">
          <el-table-column prop="名称" type="index" width="50" />
          <el-table-column prop="名称" label="名称" />
          <el-table-column prop="手机号" label="手机号" />
          <el-table-column prop="身份证" label="身份证" />
          <el-table-column prop="密码" label="密码" />
          <el-table-column prop="团队id" label="团队id" />
          <el-table-column prop="团队名称" label="团队名称" />
          <el-table-column prop="团队角色" label="团队角色" />
          <el-table-column prop="备注" label="备注" />
          <el-table-column prop="学校名称" label="学校名称" />
          <el-table-column prop="错误" fixed="right" label="错误">
            <template #default="scope">
              <el-tooltip
                v-if="!!scope.row.iserror"
                class="item"
                effect="dark"
                :content="scope.row.iserror"
                placement="top-start"
              >
                <el-button
                  v-show="scope.row.iserror"
                  type="warning"
                  size="default"
                >
                  警告
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row class="margin-top20">
      <el-col>
        <h6>团队列表</h6>
        <el-table :data="team" style="width: 100%" max-height="500">
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="userid" label="团队负责人">
            <template #default="scope">
              <div v-if="scope.row.user?.name">
                {{ scope.row.user?.name }}
              </div>
              <el-select-v2
                v-else
                v-model="scope.row.userid"
                :options="options(scope.row.name)"
                placeholder="Please select"
                style="width: 240px"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row class="margin-top20">
      <el-button
        type="primary"
        size="default"
        @click="add"
        :disabled="!tabledata.length"
        >导入</el-button
      >
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { asyncselectteams, Iobj } from "../../../api";
import { Storekey } from "../../../interface";

import { ElMessage, ElNotification } from "element-plus";
import { union } from "lodash-es";
import { some } from "underscore";
import { computed, inject, onMounted, ref, watch } from "vue";
import { useStore } from "vuex";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import {
  getExceltodownload,
  getfiletodata2,
  Sheetjsftstring,
} from "../../../util/excel";
import { isPhonenum } from "../../../util/RegExp";

const arr: string[] = [
  "名称",
  "手机号",
  "身份证",
  "密码",
  "团队id",
  "团队名称",
  "团队角色",
  "备注",
  "学校名称",
];
const tenant_id = inject<string | undefined>("tenant_id", undefined);
const p = defineProps<{ close: boolean; closeDrawer: () => {} }>();

// 码客行

onMounted(async () => {
  store.state.socket.on("api_import_user", api_import_user);
});

const data = ref<string[][]>([]);
const tabledata = computed(() => {
  return data.value.map((e) => {
    const [
      学校名称,
      名称,
      手机号,
      身份证,
      密码,
      团队id,
      团队名称,
      团队角色,
      备注,
    ] = e;
    const iserror = jc(e);
    return {
      学校名称: 学校名称 ? String(学校名称).trim() : null,
      名称: 名称 ? String(名称).trim() : null,
      手机号: 手机号 ? String(手机号).trim() : null,
      身份证: 身份证 ? String(身份证).trim() : null,
      密码: 密码 ? String(密码).trim() : "000000",
      团队id: 团队id ? String(团队id).trim() : null,
      团队名称: 团队名称 ? String(团队名称).trim() : null,
      团队角色: 团队角色 ? String(团队角色).trim() : null,
      备注,
      iserror,
    };
  });
});
const team = ref<Studycodemodel.Iteam[]>([]);
const loading = ref(false);
const groupteam = computed(() => {
  const data = tabledata.value.map((e) => [e.团队id, e.团队名称]);
  const obj: Iobj<Studycodemodel.Iteam> = {
    ID: [],
    name: [],
  };
  for (let [a, b] of data) {
    if (!obj.ID.includes(a)) {
      obj.ID.push(a);
    }
    if (!obj.ID.includes(b)) {
      obj.name.push(b);
    }
  }
  return obj;
});
watch(
  () => groupteam.value,
  async (data) => {
    changeteam(data);
  }
);

watch(
  () => p.close,
  (v) => {
    if (!v) {
      data.value = [];
    }
  }
);

async function changeteam(data: Iobj<Studycodemodel.Iteam>) {
  loading.value = true;
  const ID = data.ID;
  const name = union(data.name);
  console.log(name);
  let t: Studycodemodel.Iteam[] = [];
  if (ID.length) {
    const { rows } = await asyncselectteams({ ID });
    t = rows;
  }
  if (name.length) {
    const { rows } = await asyncselectteams({ name });
    for (const row of rows) {
      const n = t.find((e) => e.ID === row.ID);
      if (!n) {
        t.push(row);
      }
    }
    for (const row of name) {
      const n = t.find((e) => e.name === row);
      if (!n) {
        t.push({ name: row });
      }
    }
  }
  team.value = t;
  loading.value = false;
}

function options(name: string) {
  return tabledata.value
    .filter((e) => e.团队名称 === name)
    .map((e, i) => {
      return {
        value: e.名称,
        label: e.名称,
      };
    });
}

function jc(data: string[]) {
  const [
    学校名称 = "",
    名称 = "",
    手机号 = "",
    身份证 = "",
    密码 = "123456",
    团队id = "",
    团队名称 = "",
    团队角色 = "",
    备注 = "",
  ] = data;
  if (!名称) {
    return "名称不合法";
  }
  if (手机号) {
    if (!isPhonenum.test(手机号)) {
      return "手机号不合法";
    }
  } else {
    if (!身份证) {
      return "身份证或者手机必须有一个";
    }
  }
  if (密码.length < 4) {
    return "密码长度最少4位";
  }
  if (!some([团队id, 团队名称])) {
    return "团队id或者团队名称必须填写一个";
  }
  if (团队角色) {
    if (!["管理员", "学生", "教师"].includes(团队角色)) {
      return "团队角色只能是管理员、学生或者教师";
    }
  }
  return false;
}
const store = useStore(Storekey);
async function request({ file }: { file: File }) {
  data.value = await getfiletodata2<string>(file, 3);
  return true;
}

function deleteRow() {}

async function created(row: Studycodemodel.Iteam) {
  if (row.ID) return;
  if (!row.userid) {
    ElMessage.error("请选择团队创建者");
    return;
  }
}

async function add() {
  const t = tabledata.value.find((e) => e.iserror);
  if (t && typeof t.iserror === "string") {
    ElMessage.error(t.iserror);
    return;
  }
  const f = team.value.find((e) => !e.userid);
  if (f) {
    ElMessage.error(`${f.name}中没有团队创建者`);
    return;
  }
  loading.value = true;
  ElNotification({
    title: "开始添加用户",
    message: "开始添加用户",
    type: "info",
  });
  const teams: Studycodemodel.Iteam[] = team.value.map((e) => {
    const { ID, name, teamuser = [] } = e;
    const _teamuser: Studycodemodel.Iteamuser[] = tabledata.value
      .filter((f) => Number(f.团队id) == ID || name == f.团队名称)
      .map((e) => {
        const t: Record<string, Studycodemodel.Iteamuser["isAdmin"]> = {
          学生: 0,
          教师: 2,
          管理员: 1,
        };
        return {
          isAdmin: t[e?.团队角色 ? e?.团队角色 : "学生"]
            ? t[e?.团队角色 ? e?.团队角色 : "学生"]
            : 0,
          user: {
            name: e?.名称,
            password: e?.密码,
            gid: e?.身份证,
            phonenum: e?.手机号,
            remarks: e?.备注,
            info: {
              school: e?.学校名称,
            },
            xingming: e?.名称,
          },
        };
      });
    return {
      ...e,
      teamuser: _teamuser,
      // 码客行
      tenant_id,
    };
  });
  if (teams.length) {
    store.state.socket.emit("api_import_user", {
      teams,
    });
  } else {
    store.state.socket.emit("api_import_user", {
      users: tabledata.value.map((e) => {
        return {
          name: e?.名称,
          password: e?.密码,
          gid: e?.身份证,
          phonenum: e?.手机号,
          remarks: e?.备注,
          info: {
            school: e?.学校名称,
          },
          xingming: e?.名称,
          // 码客行
          tenant_id,
        };
      }),
    });
  }
}

const builddate = ref<Array<any[]>>([]);
function api_import_user(e: {
  error: number;
  data: {
    importuser: Studycodemodel.Iuser[];
    user: Studycodemodel.Iuser[];
    _erru: Studycodemodel.Iuser[];
  };
  msg: string;
}) {
  if (e.error) {
    builddate.value.push([e.msg]);
    ElMessage.error(e.msg);
    // start();
  } else {
    builddate.value.push(["注册成功用户"]);
    // builddate.value = builddate.value.concat(
    //   ...e.data.importuser
    //     .filter((_e, k) => k === 0)
    //     .map((e) => Object.keys(e))
    // );
    builddate.value = builddate.value.concat(
      e.data.importuser.map((e) => Object.values(e).map((e) => String(e)))
    );
    builddate.value.push(["之前添加成功用户"]);
    // builddate.value = builddate.value.concat(
    //   e.data.user.filter((e, k) => k === 0).map((e) => Object.keys(e))
    // );
    builddate.value = builddate.value.concat(
      e.data.user.map((e) => Object.values(e).map((e) => String(e)))
    );
    builddate.value.push(["之前添加失败用户"]);
    builddate.value = builddate.value.concat(
      e.data._erru.map((e) => Object.values(e).map((e) => String(e)))
    );
    getExceltodownload(builddate.value, "注册完成日志");
    ElMessage.success(e.msg);
    builddate.value = [];
    p.closeDrawer();
    // start();
  }
}
</script>

<style scoped>
.upload-demo {
  display: inline-block;
}

.el-table th,
.el-table td {
  text-align: center;
}

.el-button {
  margin-right: 10px;
}
</style>
